package com.ysb.common;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import java.util.Arrays;
import java.util.List;

/**
 * @author husc
 * @date 2021/3/16
 */
public class PinyinUtils {
    private static final HanyuPinyinOutputFormat HANYU_PINYIN_OUTPUT_FORMAT = new HanyuPinyinOutputFormat();
    static {
        HANYU_PINYIN_OUTPUT_FORMAT.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        HANYU_PINYIN_OUTPUT_FORMAT.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        HANYU_PINYIN_OUTPUT_FORMAT.setVCharType(HanyuPinyinVCharType.WITH_U_UNICODE);
    }

    public static List<String> getPinYin(String hanyu) {
        char[] input = hanyu.trim().toCharArray();
        StringBuilder pinyinBuilder = new StringBuilder();
        try {
            for (int i = 0; i < input.length; i++) {
                if (Character.toString(input[i]).matches("[\u4E00-\u9FA5]+")) {
                    String[] temp = PinyinHelper.toHanyuPinyinStringArray(input[i], HANYU_PINYIN_OUTPUT_FORMAT);
                    pinyinBuilder.append(temp[0]);

                    if (i != input.length - 1) {
                        pinyinBuilder.append(",");
                    }
                }
                // 忽略非中文字符
//                else {
//                    pinyinBuilder.append(input[i]);
//                }
            }
        } catch (BadHanyuPinyinOutputFormatCombination e) {
            e.printStackTrace();
        }
        String[] pinyin = pinyinBuilder.toString().split(",");
        List<String> pinyins = Arrays.asList(pinyin);
        return pinyins;
    }

    public static void main(String[] args) {
        List<String> pinYins = PinyinUtils.getPinYin("明天会hello world 更好!");
        System.out.println("pinYins = " + pinYins);
    }
}
